import axios, { AxiosInstance, AxiosError, AxiosResponse, AxiosRequestConfig } from 'axios';
import {
    ElMessage,
    ElMessageBox
} from "element-plus";
import router from "@/router"
import { usePermissStore } from "../store/permiss";
import { logoutSystem } from "@/utils";
// 是否显示重新登录
export let isRelogin = { show: false };

const permiss = usePermissStore();
const service: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_APP_WEB_API,
    timeout: 5000,
});

service.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        let token = sessionStorage.getItem("token")
        if (token) {
            if (config.headers) {
                config.headers.token = token;
            }
        } else {
            // router.push("/login")
            logoutSystem(permiss, router)
        }
        return config;
    },
    (error: AxiosError) => {
        console.log(error);
        return Promise.reject(error);
    }
);

service.interceptors.response.use(
    (response: AxiosResponse) => {
        // console.log("response：", response)
        if (response.status === 200) {
            if (response.data.code == 500) {
                ElMessage.error(response.data.msg)
            }
            return response;
        } else {
            console.log("response.data.msg", response.data.msg)
            ElMessage.error(response.data.msg)
        }
       
    },
    (error: AxiosError) => {
        console.log(error);
        if (error.response && error.response.data) {
            const result:any = error.response.data;
            if (!isRelogin.show) {
                isRelogin.show = true;
                if (result["code"] == 401) {
                    ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
                        confirmButtonText: '重新登录',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        isRelogin.show = false;
                        logoutSystem(permiss, router)
                    }).catch(() => {
                        isRelogin.show = false;
                    });
                    return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
                }
            }
        }

        return Promise.reject();
    }
);

export default service;
